package com.yike.order.lkl;

import com.lkl.laop.sdk.Config;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.exception.SDKException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author Sakura
 * @date 2025/4/29 16:58
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class LklSdkAutoConfig implements InitializingBean {

    private final LklSdkProperties properties;

    @Override
    public void afterPropertiesSet() {
        log.info("🌱 afterPropertiesSet 初始化...");
        try {
            Config config = new Config();
            config.setAppId(properties.getAppId());
            config.setSerialNo(properties.getSerialNo());
            config.setPriKeyPath(getPath(properties.getPriKeyPath()));
            config.setLklCerPath(getPath(properties.getLklCerPath()));
            config.setLklNotifyCerPath(getPath(properties.getLklNotifyCerPath()));
            config.setSm4Key(properties.getSm4Key());
            config.setServerUrl(properties.getServerUrl());

            log.info("拉卡拉 SDK 初始化配置：appId={}, serialNo={}, serverUrl={}",
                    properties.getAppId(), properties.getSerialNo(), properties.getServerUrl());


            LKLSDK.init(config);
            log.info("✅ 拉卡拉 SDK 初始化成功");
        } catch (SDKException e) {
            log.error("❌ 拉卡拉 SDK 初始化失败", e);
            throw new RuntimeException("拉卡拉 SDK 初始化失败", e);
        }
    }

    private String getPath(String resourceName) {
        try {
            URL url = this.getClass().getClassLoader().getResource(resourceName);
            if (url == null) {
                throw new FileNotFoundException(resourceName + " not found in classpath");
            }
            return URLDecoder.decode(url.getPath(), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("找不到资源文件: " + resourceName, e);
        }
    }
}
